/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.wx.video.downloadagent.handler;

import cn.ac.iie.di.ban.jr.wx.video.downloadagent.common.RuntimeEnv;
import cn.ac.iie.download.tenc.movie.GetTencMovieUrls;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class VideoDownloadExe implements Runnable {
    
    static Logger logger = Logger.getLogger(VideoDownloadExe.class.getName());
    public String respnseDir;
    public JSONObject jsonObj;
    
    public VideoDownloadExe(String respnseDir, JSONObject jsonObj) {
        this.respnseDir = respnseDir;
        this.jsonObj = jsonObj;
    }
    
    @Override
    public void run() {
        String url_md5 = null;
        long start = System.currentTimeMillis();
        String message = "";
        try {
            InputStream audioStream = null;
            boolean successFlag = false;
            String fileSuffix = ".json";
            if (jsonObj != null) {
                
                String url = jsonObj.getString("url");//真实下载地址
                url_md5 = jsonObj.getString("url_md5");

                //经过转换处理获取真实的url
                try {
                    logger.info(url_md5 + " url:" + url + ",getVid(url):" + getVid(url));
                    GetTencMovieUrls getTencMovieUrls = null;
                    try {
                        getTencMovieUrls = new GetTencMovieUrls(getVid(url));
                    } catch (Exception e) {
                        logger.error("getTencMovieUrls"+e.getMessage(), e);
                    }
                    
                    logger.info(url_md5 + " getVid " + getVid(url));
                    
                    List<String> urls = getTencMovieUrls.getUrls();
                    logger.info(url_md5 + " urls.size " + urls.size());
                    if (urls.isEmpty()) {
                        audioStream = new ByteArrayInputStream("{\"code\":-8,\"errorinfo\":\"视频文件下载失败，未获取到可用的下载url\"}".getBytes("UTF-8"));
                        logger.warn(url_md5 + " url is empty");
                    } else {
                        for (String url_true : urls) {
                            //一个个尝试下载，下载成功就不再下载
                            logger.info(url_md5 + " download url = " + url_true);
                            audioStream = downloadVideo(url_true, url_md5);
                            if (audioStream != null) {
                                fileSuffix = "";
                                successFlag = true;
                                break;
                            }
                        }
                    }
                    
                } catch (Exception e) {
                    audioStream = new ByteArrayInputStream("{\"code\":-9,\"errorinfo\":\"视频文件下载失败，真实地址获取服务异常\"}".getBytes("UTF-8"));
                    logger.error(url_md5 + " url is fail" + e.getMessage(), e);
                }
                if (audioStream == null) {
                    String responseCode = "{\"code\":-7,\"errorinfo\":\"视频文件下载失败，互联网区返回文件异常" + message + "\"}";
                    audioStream = new ByteArrayInputStream(responseCode.getBytes("UTF-8"));
                    logger.error(url_md5 + " is fail" + message + "to download");
                    successFlag = false;
                }
                //下载方法待定，视频文件较大
                //音频文件成功下载，使用原来的后缀名，否则使用json进行标明
                logger.info(url_md5 + " download flag =" + successFlag);
                
                File file = new File(respnseDir + url_md5 + fileSuffix);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                int bytesReadIn = 0;
                byte[] bytesContent = new byte[1024 * 2];
                
                while ((bytesReadIn = audioStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                    bos.write(bytesContent, 0, bytesReadIn);
                }
                bos.flush();
                fileOutputStream.close();
                bos.close();
                logger.info(file.getAbsolutePath() + " download use time (ms): " + (System.currentTimeMillis() - start));
            } else {
                logger.info(" download jsonObj is null " + (System.currentTimeMillis() - start));
            }
        } catch (IOException ex) {
            logger.error(url_md5 + ex.getMessage());
        } finally {
            logger.info("download exe time (ms): " + (System.currentTimeMillis() - start));
            
        }
        
    }
    
    public static String getVid(String url) {
        String vid = "";
        String tempString_requestMap = url.substring(url.lastIndexOf("?") + 1);
        String[] tempString_request_vid = tempString_requestMap.split("&");
        for (String temp : tempString_request_vid) {
            
            if (temp.contains("vid=")) {
                vid = temp.split("vid=")[1];
                logger.info(vid);
            }
        }
        logger.info(vid);
        return vid;
    }
    
    public static InputStream downloadVideo(String url, String url_md5) {
        InputStream audioStream = null;
        try {
            int timeOut = 1000 * Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.timeOut));
            audioStream = org.apache.http.client.fluent.Request.Get(url).
                    socketTimeout(timeOut)
                    .execute().returnContent().asStream();
        } catch (NumberFormatException | IOException ex) {
            audioStream = null;
            logger.error(url_md5 + ex.getMessage(), ex);
        }
        return audioStream;
    }
    
}
